//
//  EXRefreshControl.m
//  Exercise
//
//  Created by 羊谦 on 16/6/22.
//  Copyright © 2016年 NetEase-yangqian. All rights reserved.
//

#import "EXRefreshControl.h"

static CGFloat RefreshControlHeight = 35.f;

typedef NS_ENUM (NSUInteger,EXRefreshControlState){
    EXRefreshControlStateNormal = 0,
    EXRefreshControlStatePulling = 1,
    EXRefreshControlStateRefreshing = 2,
};


@interface EXRefreshControl ()

@property (nonatomic,strong) UIImageView *arrow;                //箭头
@property (nonatomic,strong) UIImageView *indecator;                //加载的图标
@property (nonatomic,strong) UILabel *label;
@property (nonatomic,assign) EXRefreshControlState refreshState;

@end


@implementation EXRefreshControl
{
@private
    UIScrollView *_scrollView;
    EXRefreshControlState _oldRefreshState;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.refreshState = EXRefreshControlStateNormal;
        [self setUpUI];
    }
    return self;
}

-(void)setRefreshState:(EXRefreshControlState)refreshState {
    _refreshState = refreshState;
    switch (refreshState) {
        case EXRefreshControlStateNormal: {
            // 如果之前状态是刷新状态，需要递减 contentInset.top
            if (_oldRefreshState == EXRefreshControlStateRefreshing) {
                // 重置contentInsetTop
                [UIView animateWithDuration:0.25 animations:^{
                    UIEdgeInsets contentInset = _scrollView.contentInset;
                    contentInset.top -= self.height;
                    _scrollView.contentInset = contentInset;
                }];
            }
            
            self.arrow.transform = CGAffineTransformMakeRotation(0.01);
            self.arrow.transform = CGAffineTransformIdentity;
            self.label.text = @"下拉刷新";
            self.arrow.hidden = NO;
            [self stopLoadingAnimator];
            break;
        }
        case EXRefreshControlStatePulling: {
            self.arrow.transform = CGAffineTransformMakeRotation(-0.01);
            [UIView animateWithDuration:0.25 animations:^{
                self.arrow.transform = CGAffineTransformMakeRotation((CGFloat)M_PI);
            }];
            self.label.text = @"松开刷新";
            break;
        }
            
        case EXRefreshControlStateRefreshing: {
            [UIView animateWithDuration:0.25 animations:^{
                UIEdgeInsets contentInset = _scrollView.contentInset;
                contentInset.top += self.height;
                _scrollView.contentInset = contentInset;
            }];
            self.arrow.hidden = YES;
            self.label.text = @"正在加载...";
            [self beginLoadingAnimator];
            [self sendActionsForControlEvents:UIControlEventValueChanged];
            break;
        }
            
        default:
            break;
    }
    _oldRefreshState = _refreshState;
}

- (void)setUpUI {
    
    self.height = RefreshControlHeight;
    self.top = -RefreshControlHeight;
    self.arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tableview_pull_refresh"]];
    [self addSubview:self.arrow];
    self.indecator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tableview_loading"]];
    [self addSubview:self.indecator];
    self.indecator.hidden = YES;
    self.label = [UILabel new];
    self.label.font = [UIFont systemFontOfSize:14];
    self.label.textColor = [UIColor colorWithHexString:@"ff7800"];
    self.label.text = @"下拉刷新";
    [self addSubview:self.label];
    
    [self.arrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self).offset(-30);
        make.centerY.mas_equalTo(self);
    }];
    
    [self.indecator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.arrow);
    }];
    
    [self.label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self);
        make.left.mas_equalTo(self.arrow).offset(40);
    }];
    
}

-(void)dealloc {
    [_scrollView removeObserver:self forKeyPath:@"contentOffset"];
}

-(void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];
    if ([newSuperview isKindOfClass:NSClassFromString(@"UIScrollView")]) {
        UIScrollView *scrollView = (UIScrollView *)newSuperview;
        [scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
        _scrollView = scrollView;
        self.width = scrollView.width;
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    // 取到顶部增加的可滑动的距离
    CGFloat contentInsetTop = _scrollView.contentInset.top;
    // 取到当前 scrollView 的偏移 Y
    CGFloat contentOffsetY = _scrollView.contentOffset.y;
    
    // 临界值
    CGFloat criticalValue = -contentInsetTop - self.height;
    
    // 在用户拖动的时候去判断临界值
    if (_scrollView.dragging) {
        if (_refreshState == EXRefreshControlStateNormal && contentOffsetY < criticalValue) {
            // 完全显示出来
            self.refreshState = EXRefreshControlStatePulling;
        }else if (_refreshState == EXRefreshControlStatePulling && contentOffsetY >= criticalValue) {
            // 没有完全显示出来/没有显示出来
            self.refreshState = EXRefreshControlStateNormal;
        }
    }else{
        // 判断如果用户已经松手，并且当前状态是.Pulling，那么进入到 .Refreshing 状态
        if (self.refreshState == EXRefreshControlStatePulling) {
            self.refreshState = EXRefreshControlStateRefreshing;
        }
    }
}

-(void)endRefresh {
    [self stopLoadingAnimator];
    self.refreshState = EXRefreshControlStateNormal;
}

//开始菊花
- (void)beginLoadingAnimator {
    
    self.indecator.hidden = NO;
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    anim.repeatCount = MAXFLOAT;
    anim.duration = 0.5;
    anim.toValue = [NSNumber numberWithDouble:2*M_PI];
    // 默认removedOnCompletion后就会移除动画
    anim.removedOnCompletion = false;
    [self.indecator.layer addAnimation:anim forKey:@"tranform"];
}

- (void)stopLoadingAnimator {
    self.indecator.hidden = YES;
    [self.indecator.layer removeAllAnimations];
}


@end
